<template>
  <div style="padding: 15px">
    <vxe-toolbar
      id="warehouseLocationId"
      :custom="{ storage: true }"
      export
      :refresh="{ query: findList }"
    >
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="settlement">结算</el-button>
        <!-- <el-button @click="upload">导入</el-button>
        <el-button :disabled="printFlag" @click="funcPrint">打印领用单</el-button> -->
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      :align="allAlign"
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"

      height="700"
      :loading="loading"
      :data="tableData"
      :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }"
      sort-config.remote
      @sort-change="sortList"
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="status"
          title="状态"
          min-width="100"
          sortable
          show-header-overflow
          show-overflow
          :formatter="formatterStatus"
        />
        <template v-slot:header="{ column }">
          <el-select
            v-model="listQuery.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in statusList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="warehouseName" title="仓库" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseCode" placeholder="请选择仓库 " style="width:100%" clearable>
            <el-option
              v-for="item in warehouseData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="shipmentName" title="入驻商" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.shipmentName" placeholder="请输入入驻商" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="sourceCode" title="单号" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.sourceCode" placeholder="请输入单号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="gmtOrder" title="订单日期" min-width="400" sortable show-header-overflow show-overflow />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtOrderRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtOrder')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="goodCode" title="商品编码" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.goodCode" placeholder="请输入商品编码" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="goodsName" title="商品名称" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.goodsName" placeholder="请输入商品名称" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="quantity" title="数量" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.quantity" placeholder="请输入数量" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="weight" title="重量（吨）" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.weight" placeholder="请输入重量（吨）" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="receiveLot" title="收货批次" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.receiveLot" placeholder="请输入收货批次" clearable />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="feeType" title="费用类型" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.feeType" placeholder="请输入费用类型" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="gmtSettledBegin" title="开始时间" min-width="400" sortable show-header-overflow show-overflow />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtSettledBeginRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtSettledBegin')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="gmtSettledEnd" title="结束时间" min-width="400" sortable show-header-overflow show-overflow />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtSettledEndRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtSettledEnd')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="billingUnit"
          title="结算单位"
          min-width="100"
          sortable
          show-header-overflow
          show-overflow
          :formatter="formatterbillingUnit"
        />
        <template v-slot:header="{ column }">
          <el-select
            v-model="listQuery.billingUnit"
            placeholder="请选择结算单位"
            clearable
          >
            <el-option
              v-for="item in billingUnitList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="unitPrice" title="单价" min-width="180" sortable />
        <template v-slot:header="{ column }">
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input v-model="listQuery.unitPriceLow" :min="0" :max="listQuery.unitPriceUp" placeholder="下限"  type='number' ref="quantity" />
            &nbsp;-&nbsp;
            <el-input  v-model="listQuery.unitPriceUp" :min="listQuery.unitPriceLow" placeholder="上限"  type='number' />
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="amountMoney" title="金额" min-width="180" sortable />
        <template v-slot:header="{ column }">
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input v-model="listQuery.amountMoneyLow"  :min="0" :max="listQuery.amountMoneyUp" placeholder="下限"  type='number' ref="quantity" />
            &nbsp;-&nbsp;
            <el-input  v-model="listQuery.amountMoneyUp"  :min="listQuery.amountMoneyLow" placeholder="上限"  type='number' />
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="settledMoney" title="已结算金额" min-width="180" sortable />
        <template v-slot:header="{ column }">
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input v-model="listQuery.settledMoneyLow"  :min="0" :max="listQuery.settledMoneyUp" placeholder="下限"  type='number' ref="quantity" />
            &nbsp;-&nbsp;
            <el-input  v-model="listQuery.settledMoneyUp"  :min="listQuery.settledMoneyLow" placeholder="上限"  type='number' />
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="waitingSettledMoney" title="待结算金额" min-width="180" sortable />
        <template v-slot:header="{ column }">
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input v-model="listQuery.waitingSettledMoneyLow"  :min="0" :max="listQuery.waitingSettledMoneyUp" placeholder="下限"  type='number' ref="quantity" />
            &nbsp;-&nbsp;
            <el-input  v-model="listQuery.waitingSettledMoneyUp"  :min="listQuery.waitingSettledMoneyLow" placeholder="上限"  type='number' />
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="unsettledMoney" title="未结算金额" min-width="180" sortable />
        <template v-slot:header="{ column }">
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input v-model="listQuery.unsettledMoneyLow"  :min="0" :max="listQuery.unsettledMoneyUp" placeholder="下限"  type='number' ref="quantity" />
            &nbsp;-&nbsp;
            <el-input  v-model="listQuery.unsettledMoneyUp"  :min="listQuery.unsettledMoneyLow" placeholder="上限"  type='number' />
          </el-row>
        </template>
      </vxe-table-column>
      <!-- <vxe-table-column>
        <vxe-table-column field="thisSettledMoney" title="本次结算金额" min-width="180" sortable />
      </vxe-table-column> -->
      <vxe-table-column field="thisSettledMoney" title="本次结算金额" min-width="180" :edit-render="{autofocus: '.vxe-input--inner'}">
        <template v-slot:edit="{ row }">
          <vxe-input type="number" v-model="row.thisSettledMoney" :min="0" :max="row.unsettledMoney"></vxe-input>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="remarks" title="备注" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.remarks" placeholder="请输入备注" clearable />
        </template>
      </vxe-table-column>

      <vxe-table-column title="操作" fixed="right" min-width="150">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top" v-if="scope.row.status == 'UNSETTLED' && scope.row.isShow == 0">
            <vxe-button type="text" @click="funcEdit(scope.row.code)">
              <i class="el-icon-edit"/>
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top" v-if="scope.row.status == 'UNSETTLED' && scope.row.isShow == 0">
            <vxe-button type="text" @click="funcDelete(scope.row.code)">
              <i class="el-icon-delete"/>
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total',
      ]"
      @page-change="handlePageChange"
    />
    <vxe-modal v-model="modelEditFlag" title="编辑" width="1100" height="650" resize>
      <compEdit ref="editRef" @fatherEditMethod="fatherEdit" />
    </vxe-modal>

  </div>
</template>
<script>
import Vue from "vue";
import "xe-utils";
import VXETable from "vxe-table";
import "vxe-table/lib/index.css";
import XEUtils from "xe-utils";
import VXEUtils from "vxe-utils";
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ["cookie"] });
import { allocationList, allocationBlank } from "@/api/store";
import { getWarehouse, findShipmentPartys } from "@/api/basicInfo";
import { expenseDetailList,settlement,expenseDetailDelete} from "@/api/settlement";
  import compEdit from './components/expenseDetailEdit.vue'

export default {
  name: "expenseDetailList",
  components: {
    compEdit
  },
  data() {
    return {
      message: "",
      // 日期选项
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      billingUnitList: [
        { code: "PIECE", name: "件" },
        { code: "TON", name: "吨" },
        { code: "AREA", name: "面积" },
        { code: "LOCATION", name: "库位" },

      ],
      statusList: [
        //状态
        { code: "UNSETTLED", name: "未结算" },
        { code: "SETTLED", name: "已结算" },
        { code: "PARTIALLY_SETTLED", name: "部分结算" },
      ],
      warehouseData: [],
      shipmentData: [],
      typeList: [],
      dictType: "allocationType",
      loading: false,
      allAlign: "center",
      tableData: [],
      gmtSettledBeginRange: false,
      gmtSettledEndRange: false,
      modelCheckFlag: false,
      modelPrintFlag: false,
      modelEditFlag: false,

      modelUploadFlag: false,
      initFinishFlag: false,
      copy: false,
      gmtApprovedRange: "",
      gmtOrderRange: "",
      gmtVerifyRange:'',
      gmtModifiedRange: "",
      listQuery: {
        total: 0, //总数
        createdBy: "", //创建人
        modifiedBy: "", //修改人
        code: "", //收货单号 ,
        remarks: "", //备注 ,
        billingUnit:'',
        shipmentCode: "", //入驻商 ,
        status: "", //状态 ,
        totalQuantity: "", //订货数量 ,
        type: "", //单据类型 ,
        warehouseCode: "", //仓库
        allocationBy: "",
        targetWarehouseCode:'',
        verifyName:'',
        sourceWarehouseCode:'',
        shipmentName:'',
        actualQuantity: "",
        gmtVerify:'',
        approvedBy: "",
        pageNum: 1,
        thisSettledMoney:'',
        pageSize: 10,
        sortField: "",
        sourceCode:'',
        sortType: "",
        totalQuantityFloor: "", //总数量
        totalQuantityCeiling: "",
        totalActualQuantityFloor: "", //实际领取数量
        totalActualQuantityCeiling: "",
        totalUnitQuantityFloor: "", //总数量
        totalUnitQuantityCeiling: "",
        totalActualUnitQuantityFloor: "", //实际领取数量
        totalActualUnitQuantityCeiling: "",
        allocationUnitQuantity:"",
        allocationUnitQuantityFloor:'',
        allocationUnitQuantityCeiling:'',
        outboundUnitQuantity:"",
        outboundUnitQuantityFloor:'',
        outboundUnitQuantityCeiling:'',
        inboundUnitQuantity:"",
        inboundUnitQuantityFloor:'',
        inboundUnitQuantityCeiling:'',

      },
    };
  },
  created() {
    this.getWarehouse().then(() => {
      this.getShipmentParties();
      this.findList()
    });
  },
  methods: {
      // 删除方法
      funcDelete(row) {
        this.$confirm('确认删除吗？').then(_ => {
          expenseDetailDelete(row).then(response => {
            this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
            this.findList()
          })
        }).catch(_ => {
        })
      },

    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0];
        this.listQuery[`${prefix}End`] = value[1];
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    // 入驻商查询
    getShipmentParties() {
      findShipmentPartys().then((response) => {
        this.shipmentData = response.data;
      });
    },
    // 仓库查询
    getWarehouse() {
      return getWarehouse().then((response) => {
        this.warehouseData = response.data;
      });
    },
      // 修改方法
      funcEdit(code) {
        this.$refs.editRef.getInfo(code)
        this.modelEditFlag = true
      },
      // 编辑组件的父方法
      fatherEdit() {
        this.modelEditFlag = false
        this.findList()
      },
    //结算
    settlement() {
			let selectRecords = this.$refs.xTable.getSelectRecords();
			if(selectRecords.length < 1){
				this.$message({ message: '请选择结算单', type: 'warning' });
				return false;
			}
			for (let i = 0; i < selectRecords.length; i++) {
				if (
					selectRecords[i].thisSettledMoney == 0
				) {
					this.$message({ message: '本次结算金额不能为0', type: 'warning' });
					return false;
				}
			}
			let  settlementItems = []
			for (let value of selectRecords) {
				settlementItems.push({ code: value.code, thisSettledMoney: value.thisSettledMoney });
			}
			this.loading = true
			settlement({settlementItems: settlementItems}).then(response => {
				this.$message({ message: response.msg, type: 'success' });
				this.loading = false
				this.findList()
			}).catch(_ => {
				this.loading = false
			})
    },
    // 翻译状态
    formatterStatus({ cellValue }) {
      if (cellValue == "UNSETTLED") {
        return "未结算";
      }
      if (cellValue == "SETTLED") {
        return "已结算";
      }
      if (cellValue == "PARTIALLY_SETTLED") {
        return "部分结算";
      }
    },
    formatterbillingUnit({ cellValue }) {
      if (cellValue == "PIECE") {
        return "件";
      }
      if (cellValue == "TON") {
        return "吨";
      }
      if (cellValue == "LOCATION") {
        return "库位";
      }
      if (cellValue == "AREA") {
        return "面积";
      }
    },
    //获取列表
    findList() {
      this.loading = true;
      return expenseDetailList(this.listQuery).then((response) => {
        response.data.records.forEach( i => {
          i.thisSettledMoney = i.unsettledMoney
          if(i.waitingSettledMoney == 0){
            i.isShow = 0
          }else{
            i.isShow = 1
          }
        })
        this.tableData = response.data.records;
        console.log(this.tableData)
        this.listQuery.total = response.data.total;
        this.loading = false;
      }).catch(_ => {
				this.loading = false
			});
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property;
        this.listQuery.sortType = order;
      } else {
        this.listQuery.sortField = "";
      }
      this.findList();
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case "check":
          this.modelCheckFlag = false;
          break;
        default:
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage;
      this.listQuery.pageSize = pageSize;
      this.findList();
    },
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return "合计";
          }
          if (["pageviews", "forecast"].includes(column.property)) {
            return XEUtils.sum(data, column.property);
          }
          return null;
        }),
      ];
    },
  },
  computed: {
    printFlag: function () {
      if (this.initFinishFlag) {
        let selectRecords = this.$refs.xTable.getCheckboxRecords();
        if (selectRecords.length > 0) {
          return false;
        } else {
          return true;
        }
      }
      return true;
    },
  },
};
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis),
.vxe-table .vxe-footer--column:not(.col--ellipsis),
.vxe-table .vxe-header--column:not(.col--ellipsis) {
  padding: 6px 0;
}
.vxe-toolbar {
  padding: 0 0 10px 0;
}
</style>
